<!-- src/views/CartView.vue -->
<template>
  <div class="cart-page">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 购物车标题 -->
    <div class="cart-title">
      <h1>我的购物车</h1>
    </div>

    <!-- 购物车商品列表 -->
    <div class="cart-items" v-if="userCartItems.length > 0">
      <el-table :data="userCartItems" style="width: 100%">
        <el-table-column label="商品图片" width="120">
          <template #default="scope">
            <img :src="scope.row.gImage" alt="商品图片" style="width: 100px; height: auto;" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="180">
          <template #default="scope">
            {{ scope.row.gName }}
          </template>
        </el-table-column>
        <el-table-column label="价格" width="100">
          <template #default="scope">
            ￥{{ scope.row.gPrice }}/斤
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100">
          <template #default="scope">
            <input
              type="number"
              v-model="scope.row.quantity"
              min="1"
              @change="updateQuantity(scope.row.id, scope.row.quantity)"
            />
          </template>
        </el-table-column>
        <el-table-column label="小计" width="100">
          <template #default="scope">
            ￥{{ (scope.row.gPrice * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <span class="delete-link" @click="removeItem(scope.row.id)">删除</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部结算区域 -->
      <div class="cart-footer">
        <div class="total-price">
          <span>总价：￥{{ userCartTotal.toFixed(2) }}</span>
        </div>
        <div class="action-buttons">
          <span class="continue-shopping" @click="goToHome">继续购物</span>
          <span class="checkout-link" @click="openCheckoutDialog">去结算</span>
        </div>
      </div>
    </div>

    <!-- 购物车为空时的提示 -->
    <div class="empty-cart" v-else>
      <p>购物车为空，快去挑选商品吧！</p>
      <router-link to="/home" class="go-to-home">返回首页</router-link>
    </div>

    <!-- 去结算弹窗 -->
    <el-dialog v-model="dialogVisible" title="确认订单" width="800px" :show-close="true">
      <!-- 收件人信息 -->
      <div class="dialog-header">
        <div class="form-group">
          <label>收件人：</label>
          <input 
            type="text" 
            v-model="recipientName" 
            placeholder="请输入收件人姓名"
            class="form-input"
          />
        </div>
        
        <div class="form-group">
          <label>手机号码：</label>
          <input 
            type="text" 
            v-model="recipientPhone" 
            placeholder="请输入手机号码"
            class="form-input"
            maxlength="11"
          />
        </div>
        
        <div class="form-group">
          <label>寄送地址：</label>
          <!-- 使用可编辑 span -->
          <span
            ref="addressSpan"
            class="editable-address"
            contenteditable="true"
            @blur="saveAddressToStore"
            @keydown.enter.prevent="saveAddressToStore"
            @input="onAddressInput"
            @compositionstart="onCompositionStart"
            @compositionend="onCompositionEnd"
            @focus="onAddressFocus"
            @paste="onAddressPaste"
            v-html="addressDisplay"
            :class="{
              placeholder: isPlaceholder,
              'invalid-address': isInvalidAddress,
              'valid-address': isValidAddress
            }"
          ></span>
        </div>

        <!-- 实时提示信息 -->
        <div class="address-hint" v-if="!isPlaceholder">
          <span v-if="isInvalidAddress" class="hint invalid">地址必须包含中文字符</span>
          <span v-else class="hint valid">地址格式正确</span>
        </div>
      </div>

      <!-- 商品列表 -->
      <el-table :data="userCartItems" style="width: 100%; margin-top: 20px">
        <el-table-column label="商品图片" width="100">
          <template #default="scope">
            <img :src="scope.row.gImage" alt="商品图片" style="width: 80px; height: auto;" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="150">
          <template #default="scope">
            {{ scope.row.gName }}
          </template>
        </el-table-column>
        <el-table-column label="价格" width="100">
          <template #default="scope">
            ￥{{ scope.row.gPrice }}/斤
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100">
          <template #default="scope">
            {{ scope.row.quantity }}
          </template>
        </el-table-column>
        <el-table-column label="小计" width="100">
          <template #default="scope">
            ￥{{ (scope.row.gPrice * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 总价 -->
      <div class="dialog-footer">
        <div class="total-price">
          <span>总价：￥{{ userCartTotal.toFixed(2) }}</span>
        </div>
        <div class="dialog-actions">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCheckout">确认下单</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 猜你喜欢 -->
    <div class="recommendations" v-if="userCartItems.length === 0 || showRecommendations">
      <h3>猜你喜欢</h3>
      <div class="recommendation-cards">
        <div
          class="card"
          v-for="item in recommendedItems"
          :key="item"
          @click="goToProductDetail(item)"
        >
          <img :src="getImageUrl(item)" :alt="item" @error="handleImageError" />
          <p>{{ item }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import TopNav from '@/components/TopNav.vue'
import goodApi from '@/api/controller'
import pingguo from '@/assets/images/pingguo.jpg'
import niunai from '@/assets/images/niunai.jpg'
import jidan from '@/assets/images/jidan.jpg'
import xifashui from '@/assets/images/xifashui.jpg'
import zhijin from '@/assets/images/zhijin.jpg'
import placeholder from '@/assets/images/placeholder.jpg'

const store = useStore()
const router = useRouter()

// 获取当前用户信息
const userInfo = computed(() => store.getters.getUserInfo)

// 获取当前用户的购物车商品
const userCartItems = computed(() => {
  if (!userInfo.value.username) return []
  const userCartKey = `cart_${userInfo.value.username}`
  return JSON.parse(localStorage.getItem(userCartKey) || '[]')
})

// 计算当前用户购物车总金额
const userCartTotal = computed(() => {
  return userCartItems.value.reduce((total, item) => total + (item.gPrice * item.quantity), 0)
})

// 弹窗控制
const dialogVisible = ref(false)
const address = ref('')
const isPlaceholder = ref(true)
const recipientName = ref('')  // 收件人默认为空
const recipientPhone = ref('') // 电话默认为空

// 控制是否显示推荐商品
const showRecommendations = ref(true)

// 推荐商品列表
const recommendedItems = ['苹果', '牛奶', '鸡蛋', '洗发水', '纸巾']

// 图片映射表
const imageMap = {
  '苹果': pingguo,
  '牛奶': niunai,
  '鸡蛋': jidan,
  '洗发水': xifashui,
  '纸巾': zhijin,
  'placeholder': placeholder
}

// 获取商品图片URL
function getImageUrl(keyword) {
  return imageMap[keyword] || imageMap['placeholder']
}

// 处理图片加载错误
function handleImageError(event) {
  event.target.src = imageMap['placeholder']
}

// 输入法组合状态
const isComposing = ref(false)

// 计算属性：显示的地址内容
const addressDisplay = computed(() => {
  return isPlaceholder.value ? '点击填写地址' : address.value
})

// 地址状态
const isInvalidAddress = ref(false)
const isValidAddress = ref(false)

// 地址 span 的 ref
const addressSpan = ref(null)

// 输入法开始组合
const onCompositionStart = () => {
  isComposing.value = true
}

// 输入法结束组合
const onCompositionEnd = (event) => {
  console.log(event)
  isComposing.value = false
  setTimeout(() => {
    onAddressInput()
  }, 0)
}

// 实时监测地址内容
const onAddressInput = () => {
  if (isComposing.value) {
    return
  }

  const el = addressSpan.value
  if (!el) return

  const newAddress = el.innerText.trim()
  
  if (!newAddress) {
    isPlaceholder.value = true
    address.value = ''
  } else {
    isPlaceholder.value = false
    address.value = newAddress
  }

  const hasChinese = /[\u4e00-\u9fa5]/.test(newAddress)
  isInvalidAddress.value = !hasChinese && newAddress.length > 0
  isValidAddress.value = hasChinese && newAddress.length > 0
  
  if (!isPlaceholder.value) {
    nextTick(() => {
      if (addressSpan.value) {
        moveCursorToEnd(addressSpan.value)
      }
    })
  }
}

// 聚焦时处理
const onAddressFocus = () => {
  if (isPlaceholder.value) {
    isPlaceholder.value = false
    nextTick(() => {
      if (addressSpan.value) {
        addressSpan.value.innerText = ''
        moveCursorToEnd(addressSpan.value)
      }
    })
  } else {
    nextTick(() => {
      if (addressSpan.value) {
        moveCursorToEnd(addressSpan.value)
      }
    })
  }
}

// 粘贴事件处理
const onAddressPaste = (e) => {
  e.preventDefault()
  const text = e.clipboardData.getData('text/plain')
  document.execCommand('insertText', false, text)
  
  nextTick(() => {
    if (addressSpan.value) {
      moveCursorToEnd(addressSpan.value)
    }
  })
}

// 更新商品数量
const updateQuantity = (itemId, quantity) => {
  if (quantity < 1) {
    removeItem(itemId)
    return
  }
  
  // 更新当前用户的购物车
  const userCartKey = `cart_${userInfo.value.username}`
  let userCart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
  const item = userCart.find(item => item.id === itemId)
  if (item) {
    item.quantity = quantity
    localStorage.setItem(userCartKey, JSON.stringify(userCart))
  }
}

// 删除商品
const removeItem = (itemId) => {
  // 从当前用户的购物车中移除商品
  const userCartKey = `cart_${userInfo.value.username}`
  let userCart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
  userCart = userCart.filter(item => item.id !== itemId)
  localStorage.setItem(userCartKey, JSON.stringify(userCart))
}

// 返回首页
const goToHome = () => {
  router.push('/home')
}

// 打开结算弹窗
const openCheckoutDialog = () => {
  if (userCartItems.value.length === 0) {
    alert('购物车为空，无法结算')
    return
  }
  dialogVisible.value = true
  
  // 重置表单数据，确保收件人和电话都为空
  recipientName.value = ''
  recipientPhone.value = ''
  address.value = ''
  isPlaceholder.value = true
  
  // 从 localStorage 获取地址列表，使用其中选中的地址
  if (userInfo.value.username) {
    const userAddressKey = `addressList_${userInfo.value.username}`
    const savedAddressList = localStorage.getItem(userAddressKey)
    if (savedAddressList) {
      try {
        const addressList = JSON.parse(savedAddressList)
        if (addressList.length > 0) {
          // 查找选中的地址索引
          const userSelectedAddressKey = `selectedAddressIndex_${userInfo.value.username}`
          const selectedAddressIndex = localStorage.getItem(userSelectedAddressKey)
          let selectedAddress = null
          
          if (selectedAddressIndex !== null) {
            const index = parseInt(selectedAddressIndex)
            if (index >= 0 && index < addressList.length) {
              selectedAddress = addressList[index]
              
              // 使用选中的地址信息
              recipientName.value = selectedAddress.name || ''
              recipientPhone.value = selectedAddress.phone || ''
              address.value = selectedAddress.detail || ''
              isPlaceholder.value = !address.value
            }
          }
        }
      } catch (e) {
        console.error('解析地址列表失败:', e)
      }
    }
  }
  
  nextTick(() => {
    isPlaceholder.value = !address.value
    
    if (address.value && addressSpan.value) {
      moveCursorToEnd(addressSpan.value)
    }
  })
}

// 保存地址到 store 和 localStorage
const saveAddressToStore = () => {
  if (isComposing.value) {
    return
  }

  const el = addressSpan.value
  if (!el) return

  let newAddress = el.innerText.trim()
  
  if (newAddress === '点击填写地址') {
    newAddress = ''
  }
  
  if (!newAddress) {
    isPlaceholder.value = true
    address.value = ''
  } else {
    address.value = newAddress
  }

  const hasChinese = /[\u4e00-\u9fa5]/.test(newAddress)
  if (!hasChinese && newAddress) {
    alert('地址必须包含中文字符')
    return
  }

  // 不再使用 Vuex 保存地址，直接保存到 localStorage
  if (userInfo.value.username) {
    // 保存地址到当前选中的地址项
    const userAddressKey = `addressList_${userInfo.value.username}`
    const savedAddressList = localStorage.getItem(userAddressKey)
    if (savedAddressList) {
      try {
        const addressList = JSON.parse(savedAddressList)
        if (addressList.length > 0) {
          const userSelectedAddressKey = `selectedAddressIndex_${userInfo.value.username}`
          const selectedAddressIndex = localStorage.getItem(userSelectedAddressKey)
          let index = 0
          if (selectedAddressIndex !== null) {
            index = parseInt(selectedAddressIndex)
          }
          
          if (index >= 0 && index < addressList.length) {
            addressList[index].detail = newAddress
            localStorage.setItem(userAddressKey, JSON.stringify(addressList))
          }
        }
      } catch (e) {
        console.error('更新地址失败:', e)
      }
    }
  }
}

// 确认下单
const confirmCheckout = () => {
  if (!recipientName.value.trim()) {
    alert('请输入收件人姓名')
    return
  }
  
  if (!recipientPhone.value.trim()) {
    alert('请输入手机号码')
    return
  }
  
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(recipientPhone.value)) {
    alert('请输入正确的手机号码')
    return
  }
  
  if (!address.value) {
    alert('请填写寄送地址')
    return
  }
  
  // 保存收件人信息到 localStorage
  localStorage.setItem('recipientName', recipientName.value)
  localStorage.setItem('recipientPhone', recipientPhone.value)
  
  // 创建订单对象，包含状态
  const order = {
    id: Date.now(),
    items: [...userCartItems.value],
    total: userCartTotal.value,
    recipient: recipientName.value,
    phone: recipientPhone.value,
    address: address.value,
    username: userInfo.value.username,
    date: new Date().toLocaleString(),
    status: 'pending' // 添加订单状态
  }
  
  // 将当前订单信息添加到地址列表中
  if (userInfo.value.username) {
    const userAddressKey = `addressList_${userInfo.value.username}`
    let addressList = []
    
    // 获取现有的地址列表
    const savedAddressList = localStorage.getItem(userAddressKey)
    if (savedAddressList) {
      try {
        addressList = JSON.parse(savedAddressList)
      } catch (e) {
        console.error('解析地址列表失败:', e)
      }
    }
    
    // 检查是否已经存在相同的地址信息
    const existingAddressIndex = addressList.findIndex(addr => 
      addr.name === recipientName.value && 
      addr.phone === recipientPhone.value && 
      addr.detail === address.value
    )
    
    // 如果不存在相同地址，则添加新地址
    if (existingAddressIndex === -1) {
      addressList.push({
        name: recipientName.value,
        phone: recipientPhone.value,
        detail: address.value
      })
      
      // 保存更新后的地址列表
      localStorage.setItem(userAddressKey, JSON.stringify(addressList))
      
      // 设置新添加的地址为选中状态
      const userSelectedAddressKey = `selectedAddressIndex_${userInfo.value.username}`
      localStorage.setItem(userSelectedAddressKey, (addressList.length - 1).toString())
    } else {
      // 如果地址已存在，设置为选中状态
      const userSelectedAddressKey = `selectedAddressIndex_${userInfo.value.username}`
      localStorage.setItem(userSelectedAddressKey, existingAddressIndex.toString())
    }
  }
  
  store.dispatch('saveOrder', order)
  
  // 清空当前用户的购物车
  const userCartKey = `cart_${userInfo.value.username}`
  localStorage.setItem(userCartKey, JSON.stringify([]))
  
  dialogVisible.value = false
  router.push('/order')
}

// 将光标移到元素末尾
function moveCursorToEnd(element) {
  const range = document.createRange()
  const selection = window.getSelection()
  
  range.selectNodeContents(element)
  range.collapse(false)
  
  selection.removeAllRanges()
  selection.addRange(range)
}

// 跳转到商品详情页
async function goToProductDetail(productName) {
  try {
    // 根据商品名称搜索商品
    const response = await goodApi.getGoodListPage(1, 1, productName)
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      const productId = response.rows[0].id
      router.push({ name: 'GoodsDetail', params: { id: productId } })
    } else {
      alert('未找到相关商品')
    }
  } catch (error) {
    console.error('搜索商品失败:', error)
    alert('网络异常，请稍后重试')
  }
}
</script>

<style scoped>
.cart-page {
  max-width: 1200px;
  margin: 60px auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.cart-title {
  text-align: center;
  margin-bottom: 20px;
}

.cart-items {
  margin-bottom: 40px;
}

.empty-cart {
  text-align: center;
  margin-top: 100px;
}

.empty-cart p {
  font-size: 18px;
  color: #666;
}

.go-to-home {
  display: inline-block;
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #2e7d32;
  color: white;
  border-radius: 4px;
  text-decoration: none;
}

.go-to-home:hover {
  background-color: #388e3c;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
}

.delete-link {
  color: gray;
  cursor: pointer;
}

.delete-link:hover {
  color: darkgray;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.continue-shopping {
  color: #666;
  cursor: pointer;
  font-weight: bold;
}

.continue-shopping:hover {
  color: #333;
}

.checkout-link {
  color: #2e7d32;
  cursor: pointer;
  font-weight: bold;
}

.checkout-link:hover {
  color: #388e3c;
}

.cart-items input[type="number"] {
  border: none;
  text-align: center;
  width: 50px;
  outline: none;
}

.dialog-header {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.form-group label {
  width: 80px;
  margin-right: 10px;
  font-weight: bold;
}

.form-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
}

.form-input:focus {
  border-color: #409eff;
}

.editable-address {
  display: inline-block;
  min-width: 200px;
  padding: 8px 12px;
  outline: none;
  min-height: 24px;
  background-color: #fff;
  font-size: 14px;
  color: #333;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  user-select: text;
}

.editable-address:focus {
  border-color: #409eff;
}

.editable-address.placeholder {
  color: #999;
  font-style: italic;
}

.editable-address.invalid-address {
  color: red;
  border-color: red;
}

.editable-address.valid-address {
  color: green;
  border-color: green;
}

.address-hint {
  margin-top: 6px;
  font-size: 12px;
}

.hint {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
}

.hint.invalid {
  background-color: #ffe0e0;
  color: red;
}

.hint.valid {
  background-color: #e0ffe0;
  color: green;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
}

.dialog-actions {
  display: flex;
  gap: 10px;
}

.el-dialog {
  border-radius: 10px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.el-dialog__header {
  background-color: #2e7d32;
  color: white;
  border-radius: 10px 10px 0 0;
}

.el-dialog__footer {
  background-color: #f9f9f9;
}

.el-table {
  width: 100% !important;
}

/* 推荐商品样式 */
.recommendations {
  margin-top: 40px;
  width: 100%;
}

.recommendations h3 {
  margin-bottom: 20px;
  color: #333;
}

.recommendation-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 30px;
  width: 100%;
}

.card {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: box-shadow 0.3s;
}

.card:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.card img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}
</style>